package com.bottomlord.projects.user.web.controller;

import com.bottomlord.rest.client.DefaultClientBuilder;
import com.bottomlord.web.mvc.controller.PageController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;

import static com.bottomlord.projects.user.web.controller.LoginGiteeController.*;

@Path("/login")
public class LoginController implements PageController {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String code = request.getParameter("code");

        Map<String, Object> map = new HashMap<>();
        map.put("client_secret", CLIENT_SECRET);
        Client client = DefaultClientBuilder.newClient();
        Response restResponse = client
                .target("https://gitee.com/oauth/token?grant_type=authorization_code&code=" + code + "&client_id=" + CLIENT_ID + "&redirect_uri=" + REDIRECT_URL + "&client_secret=" + CLIENT_SECRET)
                .request()
                .method(HttpMethod.POST, Entity.json(map));

        String content = restResponse.readEntity(String.class);
        System.out.println(content);

        restResponse.close();
        client.close();
        return null;
    }
}
